import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import {ComponentClass} from 'react'
import {connect} from 'react-redux'
import {View, Navigator, Image} from '@tarojs/components'
import {CityLocation, OrderItem, DistributorOrder} from '../../utils/server.interface'
import {GET_ORDER_LIST, RESOURCE_URL} from '../../constants/api'
import {user} from '../../utils/user.service';
import {getHeadTop, vcmonitor} from "../../utils/tools";
import SearchBar from "../components/header-bar/search-bar";
import {h5Wx} from "../../utils/h5.service";
import {newHttp} from "../../utils/request";
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import Index from "../components/water-mark/index";
import './list.scss'

type PageStateProps = {
  location: CityLocation
}
type PageDispatchProps = {}
type PageOwnProps = {}
type PageState = {
  tabIndex: number
  loadMoreStatus: "more" | "loading" | "noMore"
  orderList: DistributorOrder[]
  searchKey: string
  searchBarTop: number
}
type IProps = PageStateProps & PageDispatchProps & PageOwnProps

interface List {
  props: IProps
}

@connect(({location}) => ({
  location
}), (dispatch) => ({}))


class Order extends Component {
  state: PageState = {
    tabIndex: 0,
    loadMoreStatus: 'loading',
    orderList: [],
    searchKey: '',
    searchBarTop: 0,
  }
  page = 1

  async onReachBottom() {
    if (this.state.loadMoreStatus != 'noMore') {
      this.setState({loadMoreStatus: 'loading'})
      this.page++
      const orderList = await this.getData(this.page)
      const old = this.state.orderList
      if (orderList) {
        this.setState({orderList: [...old, ...orderList]})
      }
    }
  }

  async UNSAFE_componentWillMount() {
    if (process.env.TARO_ENV === 'h5') {
      await h5Wx.getConfig()
    }
    const headTop = getHeadTop()
    const searchBarTop = headTop.statusBar > 20 ? (headTop.statusBar + headTop.top + 40) : (headTop.statusBar + headTop.top + 50)
    this.setState({
      searchBarTop
    })
    const isLogin = await user.checkLogin()
    if (!isLogin) {
      Taro.showToast({
        title: '你还未登录，请登录',
        icon: 'none',
      })
      const timer = setTimeout(() => {
        clearTimeout(timer)
        Taro.switchTab({url: '/pages/my/index/index'})
      }, 1500)
      return
    }
    Taro.showLoading({title: '加载中...'})
    setTimeout(() => {
      Taro.hideLoading()
    }, 100)
  }

  async componentDidShow() {
    vcmonitor(this)
    const list = await this.getData(1)
    this.setState({orderList: list})
  }

  async getData(page) {
    const orderList = await newHttp.catchGet<OrderItem[]>(GET_ORDER_LIST, {
      pageNumber: page,
      searchKeywords: this.state.searchKey,
      orderMeal: 1
    })
    if (orderList && orderList.length === 10) {
      this.setState({loadMoreStatus: 'more'})
    } else {
      this.setState({loadMoreStatus: 'noMore'})
    }
    return orderList
  }

  searchChange(value) {
    this.setState({searchKey: value})
  }

  searchClear() {
    this.setState({searchKey: '', orderList: [], loadMoreStatus: 'loading'}, async () => {
      const orderList = await this.getData(this.page)
      this.setState({orderList})
    })
  }

  search() {
    this.page = 1
    this.setState({loadMoreStatus: 'loading', orderList: []}, async () => {
      const orderList = await this.getData(this.page)
      if (orderList) {
        this.setState({orderList})
      }
    })
  }

  render() {
    const {searchBarTop, orderList, searchKey} = this.state
    return (
      <View className='meals-list-root'>
        <Index />
        <GzhAuth />
        {process.env.TARO_ENV !== 'tt' && <View className='head-bg' style={`height: ${searchBarTop}Px;`}>
          <SearchBar color='#333' value={searchKey} searchChange={this.searchChange.bind(this)}
            searchClear={this.searchClear.bind(this)} search={this.search.bind(this)}
          />
        </View>}
        {orderList && orderList.map(item => <View key={item.id} className='order-item'>
          <Navigator  url={`/distributor/meals/detail?orderId=` + item.id}>
            <View className='order-info'>
              <Image className='img' src={item.default_img_url} mode='aspectFill' />
              <View className='name-box'>
                <View className='name'>{item.product_name}</View>
                {item.memo && <View className='valid-date'>{item.memo}</View>}
                <View className='date'>{item.add_date}</View>
                <View className='date'>所属站点：{item.site_name}</View>
              </View>
              <View className='order-info-right'>
                <View className='order-info-num'>x{item.buy_amount}</View>
                {item.pay_source_img && <Image className='order-info-from' src={item.pay_source_img} />}
              </View>
            </View>
          </Navigator>
        </View>)}
        {orderList && orderList.length <= 0 && <View className='listNull'>
          <Image src={`${RESOURCE_URL}/resources/images/shopnull.png`} mode='widthFix' />
          <View className='text'>没有任何套餐包哦~~</View>
        </View>}
      </View>
    )
  }
}

export default Order as ComponentClass<PageOwnProps, PageState>
